package com.anonymous.community;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.anonymous.community.api.ApiClient;
import com.anonymous.community.api.ApiService;
import com.anonymous.community.api.model.LoginRequest;
import com.anonymous.community.api.model.LoginResponse;
import com.anonymous.community.databinding.ActivityLoginBinding;
import com.anonymous.community.ui.base.BaseActivity;
import com.anonymous.community.utils.TokenManager;
import com.tencent.bugly.crashreport.CrashReport;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends BaseActivity {

    private ActivityLoginBinding binding;
    private ApiService apiService;
    private TokenManager tokenManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 初始化API服务和Token管理器
        apiService = ApiClient.getApiService();
        tokenManager = new TokenManager(this);

        // 检查是否已经登录
        if (tokenManager.hasValidToken()) {
            navigateToMain();
            return;
        }

        setupViews();
    }

    private void setupViews() {
        binding.btnLogin.setOnClickListener(v -> performLogin());

        binding.tvRegisterLink.setOnClickListener(v -> {
            startActivity(new Intent(this, RegisterActivity.class));
        });

        binding.tvForgotPasswordLink.setOnClickListener(v -> {
            startActivity(new Intent(this, ForgotPasswordActivity.class));
        });
    }

    private void performLogin() {
        String username = binding.etUsername.getText().toString().trim();
        String password = binding.etPassword.getText().toString().trim();

        // 验证输入
        if (TextUtils.isEmpty(username)) {
            binding.tilUsername.setError("请输入用户名");
            return;
        }
        
        if (TextUtils.isEmpty(password)) {
            binding.tilPassword.setError("请输入密码");
            return;
        }

        // 清除之前的错误信息
        binding.tilUsername.setError(null);
        binding.tilPassword.setError(null);
        hideErrorMessage();

        // 显示加载状态
        showLoading(true);

        // 创建登录请求
        LoginRequest loginRequest = new LoginRequest(username, password);

        // 发起登录请求
        apiService.login(loginRequest).enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                showLoading(false);
                
                if (response.isSuccessful() && response.body() != null) {
                    LoginResponse loginResponse = response.body();
                    
                    if (loginResponse.isSuccess()) {
                        // 登录成功，保存token和用户信息
                        String token = loginResponse.getToken();
                        TokenManager.saveToken(LoginActivity.this, token);
                        
                        // 保存用户信息
                        if (loginResponse.getUser() != null) {
                            tokenManager.saveUserInfo(
                                loginResponse.getUser().getId(),
                                loginResponse.getUser().getUsername(),
                                loginResponse.getUser().getRole()
                            );
                            
                            // 设置Bugly用户标识
                            CrashReport.setUserId(String.valueOf(loginResponse.getUser().getId()));
                            CrashReport.putUserData(getApplicationContext(), "username", loginResponse.getUser().getUsername());
                            CrashReport.putUserData(getApplicationContext(), "role", loginResponse.getUser().getRole());
                        }
                        
                        // 添加登录成功事件统计
                        CrashReport.postCatchedException(new Exception("Event: Login Success"));
                        
                        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                        navigateToMain();
                    } else {
                        showErrorMessage("登录失败");
                    }
                } else {
                    // 解析错误响应的 error 字段
                    String errorMessage = extractErrorMessage(response);
                    if (TextUtils.isEmpty(errorMessage)) {
                        errorMessage = "登录失败，请检查用户名和密码";
                    }
                    showErrorMessage(errorMessage);
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                showLoading(false);
                showErrorMessage("网络连接失败，请检查网络设置");
            }
        });
    }

    private void showLoading(boolean show) {
        binding.btnLogin.setEnabled(!show);
        binding.etUsername.setEnabled(!show);
        binding.etPassword.setEnabled(!show);
    }

    private void showErrorMessage(String message) {
        binding.tvErrorMessage.setText(message);
        binding.tvErrorMessage.setVisibility(View.VISIBLE);
    }

    private void hideErrorMessage() {
        binding.tvErrorMessage.setVisibility(View.GONE);
    }

    /**
     * 从错误响应中提取后端返回的 error 字段
     * API v3.0.0错误响应格式: { "error": "错误描述" }
     */
    private String extractErrorMessage(Response<?> response) {
        try {
            if (response != null && response.errorBody() != null) {
                String raw = response.errorBody().string();
                if (!TextUtils.isEmpty(raw)) {
                    try {
                        org.json.JSONObject obj = new org.json.JSONObject(raw);
                        if (obj.has("error")) {
                            return obj.optString("error");
                        }
                    } catch (Exception jsonEx) {
                        return raw;
                    }
                }
            }
        } catch (Exception e) {
            // 忽略解析错误
        }
        return null;
    }

    private void navigateToMain() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }

    @Override
    protected String getPageName() {
        return "登录页";
    }
}